package com.order.service.impl;


import com.order.service.impl.feign.MemberServiceFeign;
import com.order.service.impl.loadbalance.RotationLoadBalancer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


import java.util.List;

/**
 * @Description: OrderService
 * @Author: mingtian
 * @CreateDate: 2020/1/10 15:41
 * @Version: 1.0
 */
@RestController
public class OrderService {

    private final Logger LOGGER = LoggerFactory.getLogger(getClass());

    public static final String MEMBER_SERVICE_NAME = "member-service";

    public static final String API_NAME = "/getUser";


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RotationLoadBalancer loadBalance;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private MemberServiceFeign memberServiceFeign;

    @GetMapping("/orderToMember")
    public String orderToMember() {
        String uri = "http://" + "127.0.0.1:8080" + API_NAME;
        LOGGER.info("url:{}", uri);
        String result = restTemplate.getForObject(uri, String.class);
        return result;
    }

    @GetMapping("/restOrderToMember")
    public String restOrderToMember() {
        List<ServiceInstance> instances = discoveryClient.getInstances(MEMBER_SERVICE_NAME);
        //手写负载均衡算法
        ServiceInstance serviceInstance = loadBalance.getServiceInstance(instances);
        String url = serviceInstance.getUri() + API_NAME;
        LOGGER.info("url:{}", url);
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    /**
     * 返回 loadBalance 对应的信息
     *
     * @return
     */
    @GetMapping("/loadBalance")
    public Object loadBalance() {
        ServiceInstance serviceInstance = loadBalancerClient.choose(MEMBER_SERVICE_NAME);
        LOGGER.info("url:{}", serviceInstance);
        return serviceInstance;
    }

    /**
     * loadBalance
     *
     * @return
     */
    @GetMapping("/loadBalanceOrderToMember")
    public String loadBalanceOrderToMember() {
        String url = "Http://" + MEMBER_SERVICE_NAME + API_NAME;
        LOGGER.info("url:{}", url);
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }


    /**
     * feign 客户端调用
     *
     * @return
     */
    @GetMapping("/feignOrderToMember")
    public String feignOrderToMember() {
        String result = memberServiceFeign.getUserByUserId("123");
        return result;
    }


}